package com.baogulao.sendcloud.controller;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.Set;

@RestController
public class SendMailController {

    @Value("${sendcloud.apiUser}")
    private String apiUser;

    @Value("${sendcloud.apiKey}")
    private String apiKey;

    @Value("${sendcloud.fromEmail}")
    private String fromEmail;

    private String toEmail = "yami@baogulao.com";

    private final String apiUrl = "https://api.sendcloud.net/apiv2/mail/send";

    @GetMapping("/test")
    public String test() throws UnsupportedEncodingException {

        // 获取当前时间
        LocalDateTime currentTime = LocalDateTime.now();

        // 使用默认的ISO_LOCAL_DATE_TIME格式进行格式化
        String formattedDateTime = currentTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);


        // header
        MultiValueMap<String, String> requestHeader = new LinkedMultiValueMap<>();
        requestHeader.add("Content-Type", "application/x-www-form-urlencoded");

        MultiValueMap<String, String> requestData = new LinkedMultiValueMap<>();
        requestData.add("apiUser", apiUser);
        requestData.add("apiKey", apiKey);
        requestData.add("from", fromEmail);
        requestData.add("to", toEmail);
        requestData.add("subject", "sendcloud 测试邮件发送");
        requestData.add("html", "发送时间：" + formattedDateTime);

        // 将 MultiValueMap 转换为单值 Map
        Map<String, String> singleValueMap = requestData.toSingleValueMap();

        // 构建请求字符串
        StringBuilder requestString = new StringBuilder();
        for (Map.Entry<String, String> entry : singleValueMap.entrySet()) {
            if (requestString.length() > 0) {
                requestString.append("&");
            }
            requestString.append(URLEncoder.encode(entry.getKey(), "UTF-8"))
                    .append("=")
                    .append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }

        String result = httpPost(apiUrl, requestString.toString(), requestHeader.toSingleValueMap());


        return "";

    }



    public String httpPost(String url, String data, Map<String, String> heads){

        org.apache.http.client.HttpClient httpClient= HttpClients.createDefault();

        HttpResponse httpResponse = null;
        String result="";


        HttpPost httpPost=new HttpPost(url);
        if(heads!=null){
            Set<String> keySet=heads.keySet();
            for(String s:keySet){
                httpPost.addHeader(s,heads.get(s));
            }
        }

        try{
            StringEntity s=new StringEntity(data,"utf-8");
            httpPost.setEntity(s);
            httpResponse=httpClient.execute(httpPost);
            HttpEntity httpEntity=httpResponse.getEntity();
            if(httpEntity!=null){
                result= EntityUtils.toString(httpEntity,"utf-8");
            }

        }catch (IOException e){
            e.printStackTrace();

        }

        return  result;

    }
}
